<template>
  <div>
    <el-button
      size="small"
      style="margin-bottom: 4px; float: right"
      type="primary"
      @click="handleAdd()"
      >新增商品</el-button
    >
    <tableBody
      ref="table"
      :tableConfig="tableConfig"
      :queryApi="queryApi"
      :isOperate="true"
      :operateWidth="200"
    >
      <template v-slot:operate="slotProps">
        <el-button
          size="small"
          type="primary"
          @click="handleShow(slotProps.scope.row)"
          >查看</el-button
        >
        <el-button
          size="small"
          type="warning"
          @click="handleUpd(slotProps.scope.row)"
          >修改</el-button
        >
        <el-button
          size="small"
          type="danger"
          @click="handleDel(slotProps.scope.row)"
          >删除</el-button
        >
      </template>
    </tableBody>

    <el-dialog v-model="showFormVisible" title="查看商品" width="700" center>
      <div class="product">
        <h1>{{ showForm.goodsname }}</h1>
      </div>
      <div class="infos">
        <div class="thumb">
          <el-image
            style="width: 300px; height: 300px"
            :src="showForm.goodsimg"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="srcList"
            :initial-index="4"
            fit="cover"
          />
        </div>
        <div class="buy">
          <p>
            价格:<span class="price">￥{{ showForm.goodsprice }}</span>
          </p>
          <p>
            库存:<span>{{ showForm.goodsstock }}</span>
          </p>
          <p>
            状态:<span>{{ showForm.goodsstatus == 1 ? "上架" : "下架" }}</span>
          </p>
          <p>
            详情:<span>{{ showForm.goodsdetails }}</span>
          </p>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      v-model="updFormVisible"
      :title="updFormTitle"
      width="500"
      center
    >
      <el-form size="small" :model="formData" label-width="80px">
        <el-form-item label="商品名称:">
          <el-input v-model="formData.goodsname" />
        </el-form-item>
        <el-form-item label="所属分类">
          <el-cascader
            v-model="formData.categoryid"
            :options="categoryList"
            :props="props"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="headUrl">
          <el-upload
            class="avatar-uploader"
            action="/easyBuy/upload"
            :headers="headerObj"
            :show-file-list="false"
            accept="image/*"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="formData.goodsimg"
              :src="formData.goodsimg"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input
            v-model="formData.goodsprice"
            clearable
            style="width: 100px; margin-right: 4px"
          />
          元
        </el-form-item>
        <el-form-item label="库存">
          <el-input
            v-model="formData.goodsstock"
            clearable
            style="width: 100px"
          />
        </el-form-item>
        <el-form-item label="推广类别">
          <el-select style="width: 200px" v-model="formData.promotiontype">
            <el-option label="今日特价" :value="1" />
            <el-option label="热卖推荐" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveEdit()">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import tableList from "@/utils/tableBody";
import tableBody from "@/components/tableBody.vue";
import { onMounted, reactive, ref, watch } from "vue";
import { getAllCategory } from "@/api/category";
import { delGoods, addGoods, updGoods } from "@/api/goods";
import { ElMessage, ElMessageBox, UploadProps } from "element-plus";
import { CODE } from "@/utils/StatusCode";

const tableConfig = reactive(tableList.goodsList);

const queryApi = ref("/goods/getListPage");
onMounted(() => {
  query({});
  getAllCategoryList();
});
const table = ref(null);
function query(data: any) {
  (table as any).value.onSearch(data);
}

const headerObj = {
  token: localStorage.getItem("token"),
};

// 查看
const showFormVisible = ref(false);
let showForm = {
  goodsname: "",
  goodsimg: "",
  goodsprice: 0,
  goodsstock: 0,
  goodsstatus: 1,
  goodsdetails: "",
};
let srcList: string[] = [""];
function handleShow(row: any) {
  let handleRow = JSON.parse(JSON.stringify(row));
  showForm = handleRow;
  srcList[0] = showForm.goodsimg;
  showFormVisible.value = true;
}
// 修改
const props = {
  label: "categoryname",
  value: "categoryid",
};

const categoryList = ref([]);
async function getAllCategoryList() {
  const res = await getAllCategory({});
  if (res.code == CODE.OK) {
    categoryList.value = res.data;
  }
}
const updFormVisible = ref(false);
let updFormTitle = "";

interface goods {
  goodsid: number;
  categoryid: number;
  goodsname: string;
  goodsimg: string;
  goodsprice: number;
  promotiontype: number;
  goodsstatus: number;
  goodsstock: number;
  goodsdetails: string;
}
const formData = reactive<goods>({
  goodsid: 0,
  categoryid: 0,
  goodsname: "",
  goodsimg: "",
  goodsprice: 0,
  promotiontype: 0,
  goodsstock: 0,
  goodsstatus: 0,
  goodsdetails: "",
});
function handleUpd(row: any) {
  Object.keys(formData).forEach((fieId) => {
    formData[fieId] = row[fieId];
  });
  updFormVisible.value = true;
  updFormTitle = "修改商品";
}

// 清空表单
function resetForm() {
  Object.keys(formData).forEach((fieId) => {
    formData[fieId] = "";
  });
}
//新增
function handleAdd() {
  resetForm();
  updFormVisible.value = true;
  updFormTitle = "新增商品";
}
// 保存
async function saveEdit() {
  if (Array.isArray(formData.categoryid)) {
    formData.categoryid = formData.categoryid[formData.categoryid.length - 1];
  }
  let res;
  if (formData.goodsid) {
    res = await updGoods(formData);
  } else {
    res = await addGoods(formData);
  }

  if (res.code == CODE.OK) {
    ElMessage({
      message: res.message,
      type: "success",
    });
    updFormVisible.value = false;
    query({});
  } else {
    ElMessage({
      message: res.message,
      type: "error",
    });
  }
}
// 删除
function handleDel(row: any) {
  if (!row.goodsid) return;
  ElMessageBox.confirm("是否删除此商品", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await delGoods({
        goodsid: row.goodsid,
      });
      if (res.code == CODE.OK) {
        ElMessage({
          message: res.message,
          type: "success",
        });
        query({});
      } else {
        ElMessage({
          message: res.message,
          type: "error",
        });
      }
    })
    .catch(() => {});
}
const handleAvatarSuccess: UploadProps["onSuccess"] = (res, uploadFile) => {
  if (res.code == CODE.OK) {
    ElMessage({
      message: res.message,
      type: "success",
    });
    formData.goodsimg = res.data;
  } else {
    ElMessage({
      message: res.message,
      type: "error",
    });
  }
};
</script>

<style lang="less" scoped>
.product {
  font-size: 18px;
  border-bottom: 1px dashed #cfcfcf;
}
.infos {
  margin-top: 10px;
  display: flex;
  .thumb {
    width: 300px;
  }
  .buy {
    width: 440px;
    line-height: 40px;
    padding-left: 10px;
    span {
      padding-left: 4px;
    }
    .price {
      color: #c00;
      font-weight: bold;
      font-size: 24px;
    }
  }
}
:deep(.avatar-uploader) {
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
  .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  .el-upload:hover {
    border-color: var(--el-color-primary);
  }
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>
